<?php
function vote_cron() {
  _vote_cron_baidu();
}
function _vote_cron_baidu() {
  $lastid = _vote_lastid();
  $maxnum = 10; //TODO refine

  require_once ('lib/simple_html_dom.php');
  $baidu_url = 'http://apps.hi.baidu.com/vote/show/detail?vote_id=%vote_id';
  for ($i = 0; $i <= $maxnum; $i++) {
    $url = strtr($baidu_url, array ('%vote_id' => ($lastid + $i)));
    echo $url,"<br>";

    $data = _vote_get_vote_info($url);
    if ($data['status']) {
      _vote_insert($data);
      _vote_history_save(array(
        'url' => $url,
        'ctype' => 'vote',
        'status' => 1
      ));
    }

  }
  echo 'success';
}

function _vote_get_vote_info($url) {
  $data = array();

  $data['url'] = $url;

  if ($html = file_get_html($url)) {
    if ($titles = $html->find('div.app-vote-desc h1')) {
      //file_put_contents('log.log', "=={$url}\n", FILE_APPEND);

      $title = $titles[0]->innertext();
      //replace array
      $replace_title = array (
        '<img src=/static/img/spacer.gif>' => '',
        '<span class=tip>' => '',
        '</span>' => '',
        '（可多选）' => '',
        '(最多可选1项)' => '',
        '(最多可选2项)' => '',
        '(最多可选3项)' => '',
        '(最多可选4项)' => '',
        '(最多可选5项)' => '',
        '(最多可选6项)' => '',
        '(最多可选7项)' => '',
        '(最多可选8项)' => '',
        '(最多可选9项)' => '',
        '(最多可选10项)' => '',
      );
      $data['title'] = trim(strtr(mb_convert_encoding($title, 'UTF-8', 'gb2312'), $replace_title));
      //file_put_contents('log.log', 'Title: ' . mb_convert_encoding($title, 'UTF-8', 'gb2312') . "\n", FILE_APPEND);
      foreach ($html->find('#appVoteBox .vote-item-wrap h4') as $e) {
        $item = mb_convert_encoding($e->innertext(), 'UTF-8', 'gb2312');
        $data['choice'][] = $item;
        //file_put_contents('log.log', 'Item: ' . $item . "\n", FILE_APPEND);
      }
      $data['status'] = 1;
      //file_put_contents('log.log', "\n", FILE_APPEND);
    } else {
      $data['status'] = 0;
    }
  } else {
    $data['status'] = 0;
  }
  return $data;
}

function _vote_insert($data) {
  if (!isset($data['title']) || !isset($data['choice']) ||  empty($data['choice'])) {
    return FALSE;
  }

  $node = node_load(1);//TODO
  unset($node->nid);
  unset($node->vid);
  unset($node->revision_timestamp);
  unset($node->name);
  unset($node->path);
  unset($node->field_poll_id);
  unset($node->choice);
  $node->status = 1;//TODO node status
  $node->active = 1;//poll status. 1: active, 0: disable
  if ($node->active) {
    $node->allowvotes = 1;
    $node->vote = -1;
  } else {
    $node->allowvotes = '';
    unset($node->vote);
  }
  $node->uid = 3;//TODO refine
  $created = _random_time();
  $node->created = $created;
  $node->changed = $created;
  $node->title = $data['title'];
  $node->teaser = NULL;
  foreach ($data['choice'] as $index => $choice) {
    $node->choice[] = array(
      'chtext' => $choice,
      'chvotes' => 0,
      'chorder' => $index,
    );
  }

  node_save($node);
}

function _random_time($start_oclock = 5, $end_oclock = 23) {
  $hour = rand($start_oclock, $end_oclock);
  $minute = rand(0,59);
  $second = rand(0,59);
  $random = mktime($hour, $minute, $second, date('m'), date('d'), date('Y'));
  return $random;
}

function _vote_lastid() {
  $lastid = 0;
  $query = db_query("SELECT history.url AS url FROM  vote_cron_history history ORDER BY history.id DESC LIMIT 1");
  if ($url = db_result($query)) {
    $parse = parse_url($url);
    $query_string = $parse['query'];
    $query_params = explode('&', $query_string);
    foreach ($query_params as $query_param) {
      $exp = explode('=', $query_param);
      $params[$exp[0]] = $exp[1];
    }
    $lastid = $params['vote_id'];
  }
  return $lastid;
}
function _vote_history_save($data) {
  if ($data['url'] && $data['ctype'] && $data['status']) {
    db_query("INSERT INTO vote_cron_history (`url`, `ctype`, `status`) VALUES ('%s', '%s', %d)", $data['url'], $data['ctype'], $data['status']);
  }
}